$(function () {
    class shopCar {
        constructor() {
            // 获取本地登录信息
            this.usermsg = JSON.parse(sessionStorage.getItem("usermsg"));
            if (this.usermsg !== null) {
                this.writeUserMsg();
            }
            this.goodsdata = null;
            this.goodsId = [];
            // 获取本地所有数据
            this.cart_data = this.getCartData();
            if (JSON.stringify(this.cart_data) === "{}") {
                this.emptyshow()
            } else {
                this.centershow()
            }
            this.detId = "";
            this.priceall = 0;
            this.choseNum = 0;
            this.init()
            this.bindEvent()
            this.render()
        }
        init() {
            this.goodsdata = localStorage.getItem("cart")
        }
        // 根据购物车判断显示与隐藏页面内容
        emptyshow() {
            $(".cartEmpty").css({
                display: "block"
            })
            $(".center").css({
                display: "none"
            })
        }
        centershow() {
            $(".center").css({
                display: "block"
            })
            $(".cartEmpty").css({
                display: "none"
            })
        }
        bindEvent() {
            // 进入详情页
            $(".center").on("click", ".nametitle", (e) => {
                let id = $(e.target).attr("data-id")
                this.go(id);
            })

            // 删除商品
            $("#cartlist").on("click", ".del", (e) => {
                $(".delShop").css({
                    display: "block"
                })
                this.detId = "";
                let id = $(e.target).attr("data-id")
                this.detId = id;
            })
            $("#delShop").on("click", ".cancel", (e) => {
                $(".delShop").css({
                    display: "none"
                })
            })
            $("#delShop").on("click", ".noimg1", (e) => {
                $(".delShop").css({
                    display: "none"
                })
            })
            $("#delShop").on("click", ".nocancel", (e) => {
                this.delete(this.detId);
                $("input[type=checkbox]").prop("checked", false)
                $("#allprice").html("￥" + 0)
                $("#chooseNum").html(0)
                $(".delShop").css({
                    display: "none"
                })
            })

            // 改变商品数量
            // 增加数量
            $("#cartlist").on("click", ".btnincrease", (e) => {
                let id = $(e.target).attr("data-id")
                this.addCartNum(id, this.cart_data[id])
                this.init()
                $("input[type=checkbox]").prop("checked", false)
                $("#allprice").html("￥" + 0)
                $("#chooseNum").html(0)
                this.render()
            })
            // 减少数量
            $("#cartlist").on("click", ".btndecrease", (e) => {
                let id = $(e.target).attr("data-id")
                this.delCartNum(id, this.cart_data[id])
                $("input[type=checkbox]").prop("checked", false)
                $("#allprice").html("￥" + 0)
                $("#chooseNum").html(0)
                this.init()
                this.render()
            })

            // 根据复选框状态计算结算总金额
            // 根据全选按钮状态计算数据
            $("#cartlist").on("click", ".cartinput", (e) => {
                if ($(".checkAll").prop("checked")) {
                    let state = $(e.target).prop("checked")
                    let id = $(e.target).attr("data-id")
                    if (state) {
                        if (id in this.goodsId) {
                            return false;
                        } else {
                            this.goodsId.push(id)
                        }
                    } else {
                        for (var i = 0; i < this.goodsId.length; i++) {
                            if (this.goodsId[i] === id) {
                                this.goodsId.splice(i, 1)
                            }
                        }
                        if (this.goodsId.length === 0) {
                            $("input[type=checkbox]").prop("checked", false)
                        }
                    }
                    this.monerCount()
                } else {
                    let state = $(e.target).prop("checked")
                    let id = $(e.target).attr("data-id")
                    if (state) {
                        this.goodsId.push(id)
                    } else {
                        for (var i = 0; i < this.goodsId.length; i++) {
                            if (this.goodsId[i] === id) {
                                this.goodsId.splice(i, 1)
                            }
                        }
                    }
                    this.monerCount()
                }
            })

            // 全选框
            $("#cartinput").on("click", ".checkAll", (e) => {
                let state = $(e.target).prop("checked")
                if (state) {
                    $("input[type=checkbox]").prop("checked", true)
                    var allPrice = 0;
                    var chooseNum = 0;
                    this.priceall = 0;
                    this.choseNum = 0;
                    // 防止有数据缓存
                    this.goodsId = []
                    for (var key in this.cart_data) {
                        let res = this.cart_data[key].count * this.cart_data[key].price
                        allPrice += res
                        chooseNum += Number(this.cart_data[key].count)
                        this.goodsId.push(key)
                    }
                    this.priceall += allPrice;
                    this.choseNum += chooseNum;
                    $("#allprice").html("￥" + allPrice)
                    $("#chooseNum").html(chooseNum)
                } else {
                    this.goodsId = []
                    this.priceall = 0;
                    this.choseNum = 0;
                    $("input[type=checkbox]").prop("checked", false)
                    $("#allprice").html("￥" + 0)
                    $("#chooseNum").html(0)
                }
            })

            // 根据滚动条显隐右侧固定栏
            $(window).scroll((e) => {
                let scrolltop = $(document).scrollTop()
                if (scrolltop > 700) {
                    $("#fixedfield").css({
                        display: "block"
                    })
                } else {
                    $("#fixedfield").css({
                        display: "none"
                    })
                }
            }) 

            // 返回顶部
            $("#fixedfield").on("click", ".grouptop", (e) => {
                $("body,html").animate(
                    {
                        scrollTop: 0
                    },
                    800
                );
            })

            // 去结算
            $("#orderprice").on("click", ".gosettle", (e) => {
                if (this.choseNum > 0) {
                    $(".buyShop").css({
                        display: "block"
                    })
                    this.renserbuy()
                } else {
                    $(".nobuyShop").css({
                        display: "block"
                    })
                }

            })
            $("#buyShop").on("click", ".buyshoperr", (e) => {
                $(".buyShop").css({
                    display: "none"
                })
            })
            $("#buyShop").on("click", ".buyimg1", (e) => {
                $(".buyShop").css({
                    display: "none"
                })
            })

            // 未选择商品就结算
            $("#nobuyShop").on("click", ".buysuc", (e) => {
                $(".nobuyShop").css({
                    display: "none"
                })
            })
            $("#nobuyShop").on("click", ".buyimg1", (e) => {
                $(".nobuyShop").css({
                    display: "none"
                })
            })

            $("#cartEmpty").on("click", ".gopick", (e) => {
                // $(".cartEmpty").css({
                //     display: "none"
                // })
                location.href = "./list.html"
            })

        }

        // 更新选中商品总金额、总数量
        monerCount() {
            var allPrice = 0;
            var chooseNum = 0;
            this.priceall = 0;
            this.choseNum = 0;
            for (var i = 0; i < this.goodsId.length; i++) {
                let res = this.cart_data[this.goodsId[i]].count * this.cart_data[this.goodsId[i]].price
                allPrice += res
                chooseNum += Number(this.cart_data[this.goodsId[i]].count)
            }
            this.priceall += allPrice;
            this.choseNum += chooseNum;
            $("#allprice").html("￥" + allPrice)
            $("#chooseNum").html(chooseNum)
        }

        // 根据id删除商品
        delete(id) {
            delete this.cart_data[id];
            this.save()
            this.init()
            if (JSON.stringify(this.cart_data) === "{}") {
                this.emptyshow()
            } else {
                this.centershow()
            }
            this.render()

        }

        // 从本地存储获取所有商品信息数据
        getCartData() {
            try {
                let data = JSON.parse(localStorage.getItem("cart"))
                if (data === null) {
                    return {}
                }
                return data;
            } catch (e) {
                return {};
            }
        }

        // 增加购物车商品数量
        addCartNum(id, data) {
            // 判断当前的id是否存在于购物车列表之中
            if (id in this.cart_data) {
                // 如果存在就让商品数量自增; 
                this.cart_data[id].count++;
            } else {
                // 如果不存在就放入一个初始数据; 
                data.count = 1;
                this.cart_data[id] = data;
            }
            this.save();
        }

        // 减少购物车商品数量
        delCartNum(id, data) {
            // 判断当前的id是否存在于购物车列表之中
            if (id in this.cart_data) {
                // 如果存在就让商品数量自增; 
                this.cart_data[id].count--;
                if (this.cart_data[id].count === 0) {
                    this.delete(id)
                }
            } else {
                return false;
            }
            this.save();
        }

        // 根据id跳转详情页面
        go(id) {
            location.href = "./details.html#id=" + id;
        }

        // 更新本地数据
        save() {
            localStorage.setItem("cart", JSON.stringify(this.cart_data));
        }

        // 判断是否有登录信息
        writeUserMsg() {
            $(".right-login1").css({
                display: "none"
            })
            $(".right-login2").css({
                display: "inline-block"
            })
            $("#login-n").html(this.usermsg.username)
        }

        render() {
            // 获取每个map对象组合新数组
            var arr = []
            for (var key in JSON.parse(this.goodsdata)) {
                arr.push(JSON.parse(this.goodsdata)[key])
            }

            // 商品总数量
            var allNum = 0;
            for (var i = 0; i < arr.length; i++) {
                allNum += Number(arr[i].count)
            }
            $("#allNum").html(allNum)

            var $goodsshopcar = arr.map(
                item =>
                    `
                <div class="cart-item cartitem"  data-id="${item.product_id}">
                                                <div class="cartproduct">
                                                    <ul>
                                                        <li class="cart-input" >
                                                                <input type="checkbox" class="cartinput" data-id="${item.product_id}">
                                                        </li>
                                                        <li class="cart-goods">
                                                            <div class="p-pic">
                                                                <a href="#" target="_blank">
                                                                    <img src="${item.img_url}" alt="">
                                                                </a>
                                                            </div>
                                                            <div class="p-title" id="ptitle" >
                                                                <div class="nametitle" data-id="${item.product_id}">${item.product_name}<br>
                                                                    <span></span>
                                                                </div>
                                                            </div>
                                                        </li>
                                                        <li class="cart-price">${item.price}</li>
                                                        <li class="cart-num">
                                                            <div class="p-quantity">
                                                                <span class="btndecrease"  data-id="${item.product_id}">-</span>
                                                                <input type="text" name="" class="countNum" disabled value="${item.count}">
                                                                <span class="btnincrease" data-id="${item.product_id}">+</span>
                                                            </div>
                                                            <p class="goods_num_wrap"></p>
                                                        </li>
                                                        <li class="cart-discount">￥${item.is_gift}</li>
                                                        <li class="cart-point">${item.price}</li>
                                                        <li class="cart-subtotal">${item.price}</li>
                                                        <li class="cart-action" >
                                                            <div class="del" data-id="${item.product_id}">删除</div>
                                                        </li>
                                                    </ul>
                                                </div>
                
                                                <div class="cartactive">
                                                    <div class="cartgift">
                                                        <div class="p-gift">
                                                            <span class="tag">
                                                                <b>[限时优惠]</b>游戏本系列特惠！ </span>
                                                        </div>
                                                        <div class="p-gift">
                                                            <b>[赠品]</b>TUF飞行堡垒原装正品双肩包 <i>￥169 x <span
                                                                    class='pro-gift'>1</span></i>
                                                        </div>
    
                                                        <div class="p-gift">
                                                            <b>[赠品]</b>晒单咨询客服有惊喜！【单拍不发货】 <i>￥9999 x <span
                                                                    class='pro-gift'>1</span></i>
                                                        </div>
    
                                                        <div class="p-gift">
                                                            <b>[赠品]</b>【意外保】第一年不限次(赠送专用，不单独出售) <i>￥199 x <span
                                                                    class='pro-gift'>1</span></i>
                                                        </div>
    
                                                    </div>
                                                </div>
                                            </div>
                `
            ).join("")
            $("#cartlist").html($goodsshopcar)
        }

        renserbuy() {
            // var buyprice = this.shopNum * res.price
            var html = "";
            html += `共选购<span>${this.choseNum}</span>件商品，合计<span>${this.priceall}</span>元，是否继续进行结算`
            $("#buygop").html(html)
        }

    }

    new shopCar;
})